package org.cybergarage.upnp.event;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.DatagramPacket;
import java.net.MulticastSocket;

import org.cybergarage.http.HTTPRequest;
import org.cybergarage.upnp.ControlPoint;
import org.cybergarage.upnp.ssdp.HTTPMUSocket;
import org.cybergarage.upnp.ssdp.SSDP;
import org.cybergarage.util.Debug;

public class SubscriptionMUServer extends HTTPMUSocket implements Runnable {

	private ControlPoint controlPoint;
	
	
	public SubscriptionMUServer(String bindAddr){
		int eventMUPort = 50929;
		
		String addr = SSDP.ADDRESS;
		open(addr, eventMUPort, bindAddr);
	}
	
	public void setControlPoint(ControlPoint controlPoint){
		this.controlPoint = controlPoint;
	}
	
	public ControlPoint getControlPoint(){
		return this.controlPoint;
	}
	
	public void performRequestListener(HTTPRequest httpReq){
				
		if (Debug.isOn() == true)
			httpReq.print();
		
		// Thanks for Giordano Sassaroli <sassarol@cefriel.it> (09/08/03)
		if (httpReq.isNotifyRequest() == true) {
			NotifyRequest notifyReq = new NotifyRequest(httpReq);
			String uuid = notifyReq.getSID();
			long seq = notifyReq.getSEQ();
			PropertyList props = notifyReq.getPropertyList();
			int propCnt = props.size();
			for (int n = 0; n < propCnt; n++) {
				Property prop = props.getProperty(n);
				String varName = prop.getName();
				String varValue = prop.getValue();
				controlPoint.performEventListener(uuid, seq, varName, varValue);
			}
			//httpReq.returnOK();
			return;
 		}
		
		//httpReq.returnBadRequest();
		
	}
	
	public void run() {
		// TODO Auto-generated method stub
		
		
		while(true){
			Thread.yield();
			
			InputStream in = receiveHTTP();
			//annonymous
			SubscriptionMUServerThread serverThread
			   = new SubscriptionMUServerThread(this, in);
			serverThread.start();
			
			
			
		}
	}
	
	public void start(){
		Thread thread = new Thread(this);
		thread.start();
	}
	
	
	
	public InputStream receiveHTTP(){
		byte[] evenRecvBuf = new byte[SSDP.RECV_MESSAGE_BUFSIZE];
		//httpReq
		DatagramPacket dgramPkg = new DatagramPacket(evenRecvBuf, evenRecvBuf.length);
		
		try{
			MulticastSocket sock = getMulticastSocket();
			sock.receive(dgramPkg);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		
		int nData = dgramPkg.getLength();
		byte[] tmp = new byte[nData];
		byte[] data = dgramPkg.getData();
		for(int n=0; n<nData; n++){
			tmp[n] = data[n];
		}
		InputStream in = new ByteArrayInputStream(tmp);
	
		return in;
		
	}

}
